package com.bawei.module_publish.openlive.ui

import android.app.AlertDialog
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RadioButton
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.module_publish.databinding.DialogFansRedPacketBinding
import com.bawei.module_publish.openlive.intent.LiveIntent
import com.bawei.module_publish.openlive.model.entity.SendPacketBody
import com.bawei.module_publish.openlive.state.LiveState
import com.bawei.module_publish.openlive.viewmodel.LiveViewModel
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.launch

private const val TAG = "FansRedPacketDialog"
class FansRedPacketDialog constructor(private val roomId:String) : BottomSheetDialogFragment() {
    private var _binding: DialogFansRedPacketBinding? = null
    private val binding get() = _binding!!

    private var customCount = 0
    private var customDiamond = 0

    private lateinit var liveViewModel: LiveViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = DialogFansRedPacketBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
        setupConditionButtons()
        setupCountButtons()
        setupDiamondButtons()
        updateDiamondAmount()
        binding.btnSend.setOnClickListener {
            val count = getSelectedCount()
            val per = getSelectedDiamond()
            val total = count * per
            val sendRedPacketBody = SendPacketBody(count, total, roomId, 10000)
            lifecycleScope.launch {
                liveViewModel.intents.send(LiveIntent.SendRedPacket(sendRedPacketBody))
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._sendPacketFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is LiveState.SendPacketSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            ToastUtils.showLong("发送成功")
                            (parentFragment as? FansRedPacketDialog)?.dismiss()
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }

    private fun setupConditionButtons() {
        val conditionButtons = listOf(
            binding.rbFriend, binding.rbFansGroup, binding.rbFans
        )
        conditionButtons.forEach { btn ->
            btn.setOnClickListener {
                conditionButtons.forEach { it.isChecked = false }
                btn.isChecked = true
                updateCountButtonColors(conditionButtons)
            }
        }
    }

    private fun setupCountButtons() {
        val countButtons = listOf(
            binding.rbCount20, binding.rbCount50, binding.rbCount100, binding.rbCountCustom
        )
        countButtons.forEach { btn ->
            btn.setOnClickListener {
                countButtons.forEach { it.isChecked = false }
                btn.isChecked = true
                updateCountButtonColors(countButtons)
                updateDiamondAmount()
                if (btn == binding.rbCountCustom) {
                    showCustomInputDialog(btn, "自定义红包个数", "请输入红包个数") { value ->
                        customCount = value
                        btn.text = value.toString()
                        btn.isChecked = true
                        updateCountButtonColors(countButtons)
                        updateDiamondAmount()
                    }
                }
            }
        }
    }

    private fun setupDiamondButtons() {
        val diamondButtons = listOf(
            binding.rbDiamond1, binding.rbDiamond3, binding.rbDiamond10, binding.rbDiamondCustom
        )
        diamondButtons.forEach { btn ->
            btn.setOnClickListener {
                diamondButtons.forEach { it.isChecked = false }
                btn.isChecked = true
                updateCountButtonColors(diamondButtons)
                updateDiamondAmount()
                if (btn == binding.rbDiamondCustom) {
                    showCustomInputDialog(btn, "自定义人均钻石", "请输入人均钻石") { value ->
                        customDiamond = value
                        btn.text = value.toString()
                        btn.isChecked = true
                        updateCountButtonColors(diamondButtons)
                        updateDiamondAmount()
                    }
                }
            }
        }
    }

    private fun updateCountButtonColors(buttons: List<RadioButton>) {
        buttons.forEach { btn ->
            btn.isSelected = btn.isChecked // 让selector生效
        }
    }

    private fun showCustomInputDialog(targetButton: RadioButton, title: String, hint: String, onValueSet: (Int) -> Unit) {
        val editText = EditText(context)
        editText.inputType = InputType.TYPE_CLASS_NUMBER
        editText.hint = hint
        AlertDialog.Builder(requireContext())
            .setTitle(title)
            .setView(editText)
            .setPositiveButton("确定") { _, _ ->
                val value = editText.text.toString().toIntOrNull()
                if (value != null && value > 0) {
                    onValueSet(value)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun getSelectedCount(): Int {
        return when {
            binding.rbCount20.isChecked -> 20
            binding.rbCount50.isChecked -> 50
            binding.rbCount100.isChecked -> 100
            binding.rbCountCustom.isChecked -> binding.rbCountCustom.text.toString().toIntOrNull() ?: customCount
            else -> 0
        }
    }

    private fun getSelectedDiamond(): Int {
        return when {
            binding.rbDiamond1.isChecked -> 1
            binding.rbDiamond3.isChecked -> 3
            binding.rbDiamond10.isChecked -> 10
            binding.rbDiamondCustom.isChecked -> binding.rbDiamondCustom.text.toString().toIntOrNull() ?: customDiamond
            else -> 0
        }
    }

    private fun updateDiamondAmount() {
        val count = getSelectedCount()
        val per = getSelectedDiamond()
        val total = count * per
        binding.btnSend.text = "塞钱进红包 (${total}钻石)"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}